﻿#ifndef DATABASEMANAGER_H
#define DATABASEMANAGER_H

#include "common/datatypes.h" // 包含所有数据结构
#include <QSqlDatabase>
#include <QList>
#include <QString>

class DatabaseManager
{
public:
    // 构造函数会尝试打开数据库并初始化表
    DatabaseManager(const QString &dbPath = "config.db");
    ~DatabaseManager();

    // 检查数据库是否成功打开
    bool isOpen() const;

    void initTestTemplateDatabase();
    QList<OverviewItem> loadTestTemplateOverviews();
    TestTemplatePtr loadFullTestTemplate(int id);
    bool insertTestTemplate(TestTemplate &testTemplate);
    bool deleteTestTemplate(int id);
    bool updateTestTemplate(const TestTemplate &testTemplate);
    TestTemplatePtr duplicateTestTemplate(int sourceTemplateId, QString *err = nullptr);

    QList<OverviewItem> loadHardwareTemplateOverviews();
    HardwareTemplatePtr loadFullHardwareTemplate(int id);
    int getHardwareTemplateType(int id);
    bool insertHardwareTemplate(HardwareTemplate &hwTemplate);
    bool deleteHardwareTemplate(int id);
    bool updateHardwareTemplate(const HardwareTemplate &hwTemplate);
    HardwareTemplatePtr duplicateHardwareTemplate(int sourceTemplateId, QString *err = nullptr);
    bool insertDevice(DeviceConfigBase &device, int hardwareTemplateId, DeviceRole role);

    QList<OverviewItem> loadParameterTableOverviews();
    AttTableList loadAttTable(int tableId);
    TransducerTableList loadTransducerTable(int tableId);
    LimitLineList loadLimitLineTable(int tableId);
    QList<FreqTableConfig> loadFreqTable(int tableId);
    QList<CalTableConfig> loadCalibrationTable(int tableId);

    int insertNewParameterTableMeta(const QString &name, const ParamTableKind type);
    bool deleteParameterTable(int id, const ParamTableKind type);
    bool saveAttTable(int tableId, const QString &name, const AttTableList &t);
    bool saveTransducerTable(int tableId, const QString &name, const TransducerTableList &t);
    bool saveLimitLineTable(int tableId, const QString &name, const LimitLineList &t);
    bool saveFreqTable(int tableId, const QString &name, const QList<FreqTableConfig> &rows);
    bool saveCalibrationTable(int tableId, const QString &name, const QList<CalTableConfig> &rows);
    int duplicateParameterTable(int sourceTableId, ParamTableKind kind, const QString &newName, QString *err = nullptr);

private:
    void initDatabase();
    void initTableDatabase();
    void initHardwareDatabase();
    DeviceConfigBasePtr createDeviceFromQuery(QSqlQuery &query);

    bool executeQuery(QSqlQuery &query, const QString &sql, const QVariantMap &bindings = {}, const QString &context = "");

    bool executeQuery(const QString &sql, const QString &context = "");
    QString generateUniqueTemplateName(const QString &baseName, bool isTestTemplate = true);

    QSqlDatabase m_db;
};

#endif // DATABASEMANAGER_H
